package com.yequan.mybatisframework.sqlsession;

import com.yequan.mybatisframework.config.Configuration;
import com.yequan.mybatisframework.config.MappedStatement;

import java.util.List;


public class DefaultSqlSession implements SqlSession {

	private Configuration configuration;
	
	public DefaultSqlSession(Configuration configuration) {
		super();
		this.configuration = configuration;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T selectOne(String statementId, Object paramObj) {
		List<Object> list = selectList(statementId, paramObj);
		if (list != null && list.size() == 1) {
			return (T) list.get(0);
		}

		return null;
	}

	@Override
	public <T> List<T> selectList(String statementId, Object paramObj) {
		// sqlsession执行的四大组件：Executor、StatementHandler、ParameterHandler、ResultSetHandler
		
		// 根据statementId去获取MappedStatement对象
		MappedStatement mappedStatement = configuration.getMappedStatementById(statementId);
		
		// 调用Executor去执行MappedStatement对象，完成CRUD操作
		Executor executor = new CachingExecutor();
		return executor.query(mappedStatement, configuration, paramObj);
	}

}
